package com.sanyang.lawyer.utils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    //查看缓存是否存在
    public boolean isnull(String key){
        try{
            Boolean b = redisTemplate.hasKey(key);
            return b;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }

    //添加缓存
    public boolean set(String key,Object value){
        try{
            //如果存在就不添加了
            if(isnull(key)){
                return true;
            }else{
                //如果不存在就添加
                redisTemplate.opsForValue().set(key,value);
                return true;
            }
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }

    //获取缓存
    public Object get(String key){
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    //删除缓存
    public boolean delete(String ... key){
        if(key!=null && key.length>0){
            //如果是一个值
            if(key.length==1){
                redisTemplate.delete(key[0]);
            }else{
                //将数组转换成集合，批量删除
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
            return true;
        }
        return false;
    }

}

